<template>
  <div class="receipt-edit">
    <div class="page-header">
      <h2 class="page-title">编辑收货单</h2>
      <div class="actions">
        <el-button @click="goBack">
          <el-icon>
            <ArrowLeft/>
          </el-icon>
          返回
        </el-button>
        <el-button :loading="loading" type="primary" @click="submitForm">
          <el-icon>
            <Check/>
          </el-icon>
          保存
        </el-button>
      </div>
    </div>

    <el-card v-loading="loading" class="edit-card" shadow="never">
      <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="90px"
          status-icon
      >
        <el-divider content-position="left">基本信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货单编号" prop="receiptNumber">
              <el-input v-model="formData.receiptNumber" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联订单" prop="orderId">
              <el-select v-model="formData.orderId" class="w-full" filterable placeholder="选择关联订单">
                <el-option
                    v-for="order in orderOptions"
                    :key="order.id"
                    :label="order.orderNumber"
                    :value="order.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierName">
              <el-input v-model="formData.supplierName" placeholder="请输入供应商名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货日期" prop="receiptDate">
              <el-date-picker
                  v-model="formData.receiptDate"
                  class="w-full"
                  format="YYYY-MM-DD"
                  placeholder="选择收货日期"
                  style="width: 100%"
                  type="date"
                  value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货人" prop="consignee">
              <el-input v-model="formData.consignee" placeholder="请输入收货人姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" class="w-full">
                <el-option label="待验收" value="待验收"></el-option>
                <el-option label="已验收" value="已验收"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="总金额" prop="totalAmount">-->
        <!--              <el-input-number v-model="formData.totalAmount" :disabled="true" :precision="2"-->
        <!--                               style="width: 220px"></el-input-number>-->
        <!--              <span class="text-gray-500 ml-2">元 (根据商品明细自动计算)</span>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        -->

        <!--        <el-row :gutter="20">-->

        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="联系电话" prop="contactPhone">-->
        <!--              <el-input v-model="formData.contactPhone" placeholder="请输入联系电话"></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->

        <el-divider content-position="left">收货明细</el-divider>

        <div class="table-operations">
          <el-button size="small" type="primary" @click="addItem">
            <el-icon>
              <Plus/>
            </el-icon>
            添加明细
          </el-button>
        </div>

        <el-table :data="formData.items ?? []" border style="width: 100%; margin-top: 15px">
          <el-table-column align="center" label="序号" type="index" width="60"></el-table-column>

          <el-table-column label="物品名称" min-width="200">
            <template #default="{ row, $index }">
              <el-form-item
                  :prop="`items.${$index}.itemName`"
                  :rules="rules.itemName"
                  class="mb-0"
              >
                <el-input v-model="row.itemName" placeholder="请输入物品名称"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="规格" min-width="150">
            <template #default="{ row }">
              <el-form-item class="mb-0">
                <el-input v-model="row.specification" placeholder="请输入规格"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="单位" width="100">
            <template #default="{ row, $index }">
              <el-form-item
                  :prop="`items.${$index}.unit`"
                  :rules="rules.unit"
                  class="mb-0"
              >
                <el-input v-model="row.unit" placeholder="单位"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="120">
            <template #default="{ row, $index }">
              <el-form-item
                  :prop="`items.${$index}.quantity`"
                  :rules="rules.quantity"
                  class="mb-0"
              >
                <el-input-number
                    v-model="row.quantity"
                    :min="1"
                    :precision="0"
                    controls-position="right"
                    style="width: 100%"
                    @change="calculateItemAmount(row)"
                ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="单价" width="150">
            <template #default="{ row, $index }">
              <el-form-item
                  :prop="`items.${$index}.unitPrice`"
                  :rules="rules.unitPrice"
                  class="mb-0"
              >
                <el-input-number
                    v-model="row.unitPrice"
                    :min="0"
                    :precision="2"
                    :step="0.01"
                    controls-position="right"
                    style="width: 100%"
                    @change="(value) => calculateItemAmount(row)"
                ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="金额" width="150">
            <template #default="{ row }">
              <el-form-item class="mb-0">
                <el-input :value="formatCurrency(row.total)" disabled></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" width="80">
            <template #default="{ $index }">
              <el-button
                  :disabled="formData.items.length <= 1"
                  circle
                  size="small"
                  type="danger"
                  @click="removeItem($index)"
              >
                <el-icon>
                  <Delete/>
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="summary">
          <span class="summary-label">总计金额：</span>
          <span class="summary-value">{{ formatCurrency(totalAmount) }}</span>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, reactive, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage} from 'element-plus';
import {ArrowLeft, Check, Delete, Plus} from '@element-plus/icons-vue';
import type {ReceiptItem} from '@/api/types.ts';
import {getReceiptDetail, updateReceipt} from '@/api/receipt.ts';
import {getOrderList} from '@/api/order.ts';

const route = useRoute();
const router = useRouter();
const receiptId = computed(() => {
  const id = route.params.id;
  if (!id || id === 'undefined' || id === 'null' || id === 'NaN') {
    console.warn('路由参数中的ID无效:', id);
    return '';
  }
  return String(id);
});

// 表单引用
const formRef = ref<FormInstance>();
const loading = ref(false);

// 表单数据
const formData = reactive<any>({
  receiptNumber: '',
  orderId: '',
  supplierName: '',
  receiptDate: '',
  status: '',
  totalAmount: 0,
  consignee: '',
  contactPhone: '',
  items: [{
    itemName: '',
    productName: '',
    specification: '',
    unit: '',
    quantity: 1,
    unitPrice: 0,
    price: 0,
    total: 0,
    amount: 0,
    remark: ''
  }]
});

// 订单选项
const orderOptions = ref<Array<{ id: string, orderNumber: string }>>([]);

// 加载订单选项
const loadOrderOptions = async () => {
  try {
    const res = await getOrderList({pageSize: 100});
    if (res.data && res.data.records) {
      orderOptions.value = res.data.records.map(order => ({
        id: order.id as string,
        orderNumber: order.orderNumber
      }));
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
  }
};

// 表单校验规则
const rules = reactive<FormRules>({
  orderId: [
    {required: true, message: '请选择关联订单', trigger: 'change'}
  ],
  supplierName: [
    {required: true, message: '请输入供应商名称', trigger: 'blur'}
  ],
  status: [
    {required: true, message: '请选择收货单状态', trigger: 'change'}
  ],
  consignee: [
    {required: true, message: '请输入收货人姓名', trigger: 'blur'}
  ],
  itemName: [
    {required: true, message: '请输入产品名称', trigger: 'blur'}
  ],
  receiptDate: [
    {required: true, message: '请选择收货日期', trigger: 'change'}
  ],
  unit: [
    {required: true, message: '请输入单位', trigger: 'blur'}
  ],
  quantity: [
    {required: true, message: '请输入数量', trigger: 'blur'},
    {type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur'}
  ],
  unitPrice: [
    {required: true, message: '请输入单价', trigger: 'blur'},
    {type: 'number', min: 0, message: '单价不能为负数', trigger: 'blur'}
  ]
});

// 计算总金额
const totalAmount = computed(() => {
  if (!formData.items || formData.items.length === 0) {
    return 0;
  }
  return formData.items.reduce((sum, item) => {
    const itemTotal = Number(item.total || item.amount || 0);
    return sum + itemTotal;
  }, 0);
});

// 获取收货单详情
const fetchReceiptDetail = async () => {
  if (!receiptId.value) {
    console.error('收货单ID为空，无法获取详情');
    ElMessage.error('收货单ID无效，无法获取详情');
    return;
  }

  loading.value = true;
  try {
    const res = await getReceiptDetail(receiptId.value);
    if (res.data) {
      // 填充表单数据
      const detail = res.data;
      formData.id = detail.id;
      formData.receiptNumber = detail.receiptNumber;
      formData.orderId = detail.orderId;
      formData.supplierName = detail.supplierName;
      formData.status = detail.status;
      // formData.totalAmount = detail.totalAmount;
      formData.consignee = detail.consignee;
      formData.receiptDate = detail.receiptDate;
      // formData.contactPhone = detail.contactPhone;

      // 填充明细项
      if (detail.items && detail.items.length > 0) {
        formData.items = detail.items.map(item => {
          const newItem = {
            ...item,
            itemName: item.itemName || item.productName || '',
            unitPrice: item.unitPrice || item.price || 0,
            quantity: Number(item.quantity) || 0,
            price: item.price || item.unitPrice || 0
          };

          // 确保计算金额
          newItem.amount = Number(newItem.quantity) * Number(newItem.unitPrice);
          newItem.total = newItem.amount;

          return newItem;
        });
      }

      // 更新总金额
      updateTotalAmount();
    } else {
      ElMessage.warning('未找到收货单信息');
    }
  } catch (error) {
    console.error('获取收货单详情失败:', error);
    ElMessage.error('获取收货单详情失败');
  } finally {
    loading.value = false;
  }
};

// 添加商品明细项
const addItem = () => {
  if (!formData.items) {
    formData.items = [];
  }
  formData.items.push({
    itemName: '',
    productName: '',
    specification: '',
    unit: '',
    quantity: 1,
    unitPrice: 0,
    price: 0,
    total: 0,
    amount: 0
  });
};

// 移除商品明细项
const removeItem = (index: number) => {
  if (!formData.items || formData.items.length <= 1) {
    ElMessage.warning('至少需要一个商品明细');
    return;
  }
  formData.items.splice(index, 1);
  updateTotalAmount();
};

// 计算单项金额
const calculateItemAmount = (item: ReceiptItem) => {
  if (!item) return;

  const quantity = Number(item.quantity) || 0;
  const unitPrice = Number(item.unitPrice) || 0;

  item.amount = quantity * unitPrice;
  item.total = item.amount;

  if (item.price !== undefined) {
    item.price = unitPrice;
  }

  if (item.productName) {
    item.itemName = item.productName;
  }

  updateTotalAmount();
};

// 更新总金额
const updateTotalAmount = () => {
  formData.totalAmount = totalAmount.value;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  // 先检查收货单ID
  if (!receiptId.value) {
    console.error('表单提交时收货单ID为空');
    ElMessage.error('收货单ID无效，无法保存');
    return;
  }

  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.error('表单验证失败:', fields);
      ElMessage.error('请修正表单中的错误');
      return;
    }

    loading.value = true;
    try {
      // 更新总金额
      formData.totalAmount = totalAmount.value;

      // 确保orderId是有效的数字
      if (!formData.orderId) {
        console.error('订单ID为空');
        ElMessage.error('请选择关联订单');
        loading.value = false;
        return;
      }

      if (typeof formData.orderId === 'string') {
        const parsedId = parseInt(formData.orderId, 10);
        if (isNaN(parsedId)) {
          console.error('订单ID无效, 无法转换为数字:', formData.orderId);
          ElMessage.error('订单ID格式无效');
          loading.value = false;
          return;
        }
        formData.orderId = parsedId;
      }

      // 提交到服务器
      await updateReceipt(receiptId.value, formData);

      ElMessage.success('收货单更新成功');
      router.push(`/dashboard/receipt-detail/${receiptId.value}`);
    } catch (error) {
      console.error('更新收货单失败:', error);
      ElMessage.error('更新收货单失败');
    } finally {
      loading.value = false;
    }
  });
};

// 返回详情页
const goBack = () => {
  router.push(`/dashboard/receipt-detail/${receiptId.value}`);
};

// 页面加载时获取数据
onMounted(() => {
  // 先加载订单选项
  loadOrderOptions();
  // 然后获取收货单详情
  if (receiptId.value) {
    fetchReceiptDetail();
  } else {
    console.error('无法加载收货单数据：ID无效');
    ElMessage.error('无法加载收货单：ID无效');
    setTimeout(() => {
      router.push('/dashboard/receipt-list');
    }, 1500);
  }
});

// 格式化金额显示
const formatCurrency = (value: number | string) => {
  if (value === undefined || value === null || value === '') return '¥0.00';
  const num = typeof value === 'string' ? parseFloat(value) : value;
  return `¥${num.toFixed(2)}`;
};
</script>

<style scoped>
.receipt-edit {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.actions {
  display: flex;
  gap: 8px;
}

.edit-card {
  margin-bottom: 24px;
}

.table-operations {
  margin-bottom: 15px;
}

.mb-0 {
  margin-bottom: 0 !important;
}

.mb-0 :deep(.el-form-item__content) {
  margin-bottom: 0 !important;
  margin-left: 0 !important;
}

.mb-0 :deep(.el-form-item__error) {
  position: absolute;
  top: 100%;
  left: 0;
}

.w-full {
  width: 100%;
}

.summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.summary-label {
  font-weight: 500;
  margin-right: 10px;
}

.summary-value {
  font-size: 16px;
  font-weight: 600;
  color: #E6A23C;
}

/* 确保表格中所有表单项内容没有左边距和下边距 */
:deep(.el-table .el-form-item__content) {
  margin-left: 0 !important;
  margin-bottom: 0 !important;
}

:deep(.el-table .el-form-item) {
  margin-bottom: 0 !important;
}

/* 优化表格内输入框样式 */
:deep(.el-table .el-input-number) {
  width: 100%;
}

:deep(.el-table .el-input-number .el-input__wrapper) {
  padding-right: 30px !important;
}

:deep(.el-input-number__increase),
:deep(.el-input-number__decrease) {
  z-index: 2 !important;
}

:deep(.el-input-number__increase) {
  right: 1px !important;
}

:deep(.el-input-number__decrease) {
  right: 1px !important;
  top: 50% !important;
}

:deep(.el-table .cell) {
  padding: 0 5px !important;
}
</style>